package com.example.defaultshop;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class CategoryActivity extends ListActivity {
	private ArrayList<Category> categories;
	
	private SwipeRefreshLayout swipe;
	private DrawerLayout layout;
	private ListView sidemenu, list;
	private Button back, home, basket, settings;
	private Context context;

	private ShopApplication app;
	private CategoryTask task;
	
	private String[] items;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_categories);

		app = (ShopApplication) getApplicationContext();
		context = this;

		items = new String[3 + app.getCards().size()];
		for (int i = 0; i < 3 + app.getCards().size(); i++) {
			switch (i) {
			case 0:
				items[i] = "Info";
				break;
			case 1:
				items[i] = "Indstillinger";
				break;
			case 2:
				items[i] = "Genbestil ordre";
				break;
			default:
				items[i] = app.getCards().get(i - 3).getName();
				break;
			}
		}
		
		layout = (DrawerLayout) findViewById(R.id.drawer_layout);
        sidemenu = (ListView) findViewById(R.id.left_drawer);
        
        sidemenu.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, items));
        sidemenu.setOnItemClickListener(new DrawerItemClickListener());
		
        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
		swipe.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
        swipe.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				task = new CategoryTask();
				task.execute();
			}
		});
        
		list = (ListView) findViewById(android.R.id.list);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(view.getContext(), MenuActivity.class);
				intent.putExtra("category", categories.get(position));
				startActivity(intent);
			}
		});
		
		back = (Button) findViewById(R.id.btnCategoryBack);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		home = (Button) findViewById(R.id.btnCategoryHome);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), CampaignActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
		
		basket = (Button) findViewById(R.id.btnCategoryBasket);
		basket.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), BasketActivity.class);
				startActivity(intent);
			}
		});
		
		settings = (Button) findViewById(R.id.btnSettings);
		settings.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				layout.openDrawer(sidemenu);
			}
		});
		
		categories = app.getCategories();
		if (categories.size() > 0) {
			CategoryArrayAdapter adapter = new CategoryArrayAdapter(context, categories, app.getShop().getHexColor());
			list.setAdapter(adapter);
		} else {
			swipe.setRefreshing(true);
			task = new CategoryTask();
			task.execute();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if (task != null)
			if (task.getStatus() == Status.RUNNING)
				task.cancel(true);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		Calendar date = Calendar.getInstance();
		Calendar deadline = app.getShop().getDeadline();
		if (date.get(Calendar.YEAR) != deadline.get(Calendar.YEAR) || date.get(Calendar.MONTH) != deadline.get(Calendar.MONTH) || date.get(Calendar.DAY_OF_MONTH) != deadline.get(Calendar.DAY_OF_MONTH)) {
			Intent intent = new Intent(this, CampaignActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
	}
	
	private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
    	switch (position) {
		case 0:
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(Server.INFO + app.getShop().getIdx()));
			startActivity(browserIntent);
			break;
		case 1:
			Intent customer = new Intent(this, CustomerActivity.class);
			startActivity(customer);
			break;
		case 2:
			Intent order = new Intent(this, OrderActivity.class);
			startActivity(order);
			break;
		default:
			Intent card = new Intent(this, CardActivity.class);
			card.putExtra("index", position - 3);
			startActivity(card);
			break;
		}
    	
        sidemenu.setItemChecked(position, false);
        layout.closeDrawer(sidemenu);
    }
	
	private class CategoryTask extends AsyncTask<Void, Void, Boolean> {
    	@Override
		protected Boolean doInBackground(Void... params) {
    		try {
    			InputStream in = Server.post(Server.CATEGORIES, Server.getAuthenticationCategories(app.getShop().getIdx()));
    			XmlPullParser parser = Server.toXmlParser(in);
    			categories = XmlParser.getCategories(parser);
    			app.addCategories(categories);
    			in.close();
    		} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
    			return false;
    		} catch (XmlPullParserException e) {
    			Log.e("Shop", "XmlPullParserException: " + e.getMessage());
    			return false;
    		} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
    			return false;
    		} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
    		return true;
    	}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	swipe.setRefreshing(false);
	    	if (success) {
    			CategoryArrayAdapter adapter = new CategoryArrayAdapter(context, categories, app.getShop().getHexColor());
    			list.setAdapter(adapter);
	    	} else {
	    		AlertDialog.Builder builder = new AlertDialog.Builder(context);
	    		builder.setMessage(R.string.error_categories)
	    		       .setTitle(R.string.error)
	    		       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								swipe.setRefreshing(true);
								task = new CategoryTask();
								task.execute();
							}
						})
						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
	    	}
	    }
	}
}